package com.sgl.blog.service.impl;

import com.sgl.blog.mapper.AccountMapper;
import com.sgl.blog.pojo.BlogAccount;
import com.sgl.blog.service.MailService;

import com.sgl.blog.util.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * @标题：
 * @内容：
 * @作者： 宋志豪
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {
    @Resource
    private JavaMailSender mailSender;

    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private AccountMapper accountMapper;



    //邮件发件人
    @Value("${spring.mail.username}")
    private String from;

    @Override
    public String sendMail(BlogAccount blogAccount) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);


        String code = CodeUtils.code_6();
        Context context = new Context();
        context.setVariable("code", code);
        context.setVariable("username", blogAccount.getAccountEmail());
        String tempContext = templateEngine.process("emailTemplate", context);

        helper.setFrom(new InternetAddress(from,"SGL_BLOG","UTF-8"));
        helper.setTo(blogAccount.getAccountEmail());
        helper.setSubject("SGL_BLOG");

        helper.setText(tempContext,true);
        mailSender.send(message);
        log.info("邮件发送成功  邮箱：" + blogAccount.getAccountEmail() + "\t 验证码："+ code);
        return code;
    }

    @Override
    public Boolean validationEmail(BlogAccount account) {
        return accountMapper.select(account).size() != 0;
    }

}
